package service

import (
	"context"
	"mall-admin-go/dao"
	"mall-admin-go/model"
	"mall-admin-go/pkg/e"
	"mall-admin-go/pkg/util"
	"mall-admin-go/serializer"
)

type ProductService struct {
	Id            uint    `json:"id" form:"id"`
	Name          string  `json:"name" form:"name"`
	CategoryId    string  `json:"category_id" form:"category_id"`
	Title         string  `json:"title" form:"title"`
	Info          string  `json:"info" form:"info"`
	ImgPath       string  `json:"img_path" form:"img_path"`
	Price         float64 `json:"price" form:"price"`
	DiscountPrice float64 `json:"discount_price" form:"discount_price"`
	OnSale        bool    `json:"on_sale" form:"on_sale"` //商品是否在售
	Num           int64   `json:"num" form:"num"`
	model.BasePage
}

func (service *ProductService) List(ctx context.Context) interface{} {
	productDao := dao.NewProductDao(ctx)
	if service.PageNum == 0 || service.PageNum < 1 {
		service.PageNum = 1
	}
	if service.PageSize > 15 {
		service.PageNum = 15
	}
	products, total, err := productDao.GetProduct(service.BasePage)
	if err != nil {
		return serializer.ErrorResponse(e.Error)
	}
	return serializer.BuildListResponse(serializer.BuildProducts(products), uint(total), service.PageNum, service.PageSize)
}
func (service *ProductService) Add(ctx context.Context) interface{} {
	//参数校验
	if service.Name == "" || service.Title == "" || service.CategoryId == "" || service.ImgPath == "" || service.Price == 0 || service.DiscountPrice == 0 || service.Num == 0 {
		return serializer.ErrorResponse(e.InvalidParams)
	}
	//分类是否存在
	productDao := dao.NewProductDao(ctx)
	product := model.Product{
		Name:          service.Name,
		Title:         service.Title,
		Info:          service.Info,
		ImgPath:       service.ImgPath,
		Price:         service.Price,
		DiscountPrice: service.DiscountPrice,
		OnSale:        service.OnSale,
		Num:           service.Num,
		BossId:        0,
		BossName:      "",
		BossAvatar:    "",
		Total:         service.Num,
		Uuid:          util.NewUuid(),
	}
	err := productDao.Create(&product)
	if err != nil {
		return serializer.ErrorResponse(e.Error)
	}
	return serializer.SuccessResponse("添加成功")
}
